package com.dacool.view;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Movie;
import android.graphics.Paint;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

@SuppressLint("NewApi")
public class GifView extends View {

	private Movie movie;
	private long time;
	private Paint paint = new Paint();

	public GifView(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
		try {
			Method method = this.getClass().getMethod("setLayerType", int.class,Paint.class);
			method.invoke(this, LAYER_TYPE_SOFTWARE,null);
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public GifView(Context context) {
		this(context, null);
	}

	public void setResID(int resID) {
		movie = Movie.decodeStream(getResources().openRawResource(resID));
		this.postInvalidate();
	}

	@Override
	protected void onDraw(Canvas canvas) {
		if (movie != null) {
			long curTime = SystemClock.uptimeMillis();
			int duration = movie.duration();
			if (time == 0) {
				time = curTime;
			}
			int reltime = (int) ((curTime - time) % duration);

			canvas.scale(((float) this.getWidth()) / movie.width(),
					((float) this.getHeight()) / movie.height());
			movie.setTime(reltime);
			paint.setAntiAlias(true);
			movie.draw(canvas, 0, 0, paint);

		}
		super.onDraw(canvas);
		if (isShown()) {
			this.postInvalidate();
		}
	}

}
